import Dialog from './dialog.vue'
import { createApp } from 'vue'
import { getRef } from '@/components/dialog/ref'

export default function initDialog(app: any) {
  let instance:any
  app.config.globalProperties.$dialog = {
    show: async (data?: AnyObject) => {
      app.config.globalProperties.$dialogData = data
      // #ifdef H5
      if (!instance) {
        const mountNode = document.createElement('div')
        document.body.appendChild(mountNode)
        instance = createApp(Dialog).mount(mountNode)
      }
      instance.show(data)
      // #endif
      // #ifdef MP
      if (!instance) {
        instance = await getMpDialogInstance()
      }
      instance.show(data)
      // #endif
      // #ifdef APP-PLUS
      getApp().globalData!.dialogData = data
      uni.navigateTo({ url: '/components/dialog/dialog' })
      // #endif
    }
  }
}

async function getMpDialogInstance() {
  return new Promise((resolve) => {
    function _getRef() {
      const i = getRef('dialog')
      if (i) {
        resolve(i)
      } else {
        setTimeout(() => {
          _getRef()
        }, 200)
      }
    }
    _getRef()
  })
}
